package sevensoft.行为型模式;

import org.junit.Test;

import java.util.concurrent.*;

public class Demo {


    static final ThreadLocal<String> tl = new ThreadLocal<>();

    ExecutorService executorService = Executors.newFixedThreadPool(10);

    String getThreadName() {
        return Thread.currentThread().getName() + ":";
    }

    @Test
    public void test2() throws InterruptedException {
        int index = 7;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(index, () -> {
            System.out.println("召唤神龙");
        });
        for ( int i = 0; i < index; i++ ) {
            final int i1 = i;
            new Thread(() -> {
                try {
                    System.out.println(i1);
                    cyclicBarrier.await();
                }
                catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
    }

    @Test
    public void test3(){
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1000);
                System.out.println(1);
            }
            catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        thread.setDaemon(true);
        thread.start();
        System.out.println("end");
    }

    @Test
    public void test() {
        tl.set("user1");
        System.out.println(getThreadName() + tl.get());
        setThreadPool("user2");


        for ( Integer i = 0; i < 10; i++ ) {
            Integer finalI = i;
            new Thread(() -> {
                int i1 = finalI;
            }).start();
        }
    }

    void setThreadPool(String name) {
        final String constName = name;
        executorService.execute(() -> {
            Thread.currentThread().setName(constName);
            tl.set(constName);
            System.out.println(getThreadName() + tl.get());
        });
    }
}
